<template>
  <div :class="classes" :name="name">
      <slot></slot>
  </div>
</template>

<script>
import { oneOf,findComponentsDownward } from '../../utils/index';
import Emitter from '../../utils/emitter';
let seed = 0;
const now = Date.now();
const groupName=()=>`iFastCheckboxGroup_${now}_${seed++}`;

const prefixCls='ifast';
export default {
  name: "CheckboxGroup",
  mixins:[Emitter],
  props: {
    value: {
       type: Array,
       default () {
          return [];
       }
    },
    size: {
        validator (value) {
            return oneOf(value, ['sm', 'lg']);
        },
    },
    type: {
        validator (value) {
            return oneOf(value, ['button']);
        }
    },
    vertical: {
        type: Boolean,
        default: false
    },
    name: {
        type: String,
        default: groupName
    }
  },
  computed: {
    classes () {
        return [
            {
                [`${prefixCls}-group-checkbox`]:true,
                [`${this.size}`]: !!this.size,
                [`${prefixCls}-checkbox-button`]:!!this.type,
                [`${prefixCls}-checkbox-block`]: this.vertical
            }
        ];
    }
  },

  data() {
    return {
        currentValue: this.value,
        childrens: []
    };
  },

  mounted() {
    this.updateCheckboxValue(true);
  },
  methods: {
    updateCheckboxValue(update) {
      this.childrens = findComponentsDownward(this, "Checkbox");
      if (this.childrens) {
        const { value } = this;
        this.childrens.forEach(child => {
          child.model = value;
          if (update) {
              child.currentValue = value.indexOf(child.label) >= 0;
              child.group = true;
          }
        });
      }
    },
    change(data) {
      this.currentValue = data;
      //不能直接 this.updateCheckboxValue,需要等value改变之后才能执行
      this.$emit("input", data);
      this.$emit("on-change", data);
    }
  },
  watch: {
    value() {
        this.$nextTick(() => {
           this.updateCheckboxValue(true);
        });
     
    }
  }
};
</script>

<style lang='scss' scoped>
</style>
